// PDF生成模块

const { PDFDocument, rgb, degrees } = PDFLib;

// 加载字体函数 - 优先使用本地字体，失败则尝试CDN源
async function loadFont(pdfDoc) {
    // 优先尝试本地字体文件
    if (localFontFile) {
        try {
            console.log('使用本地字体文件:', localFontFile.name);
            const fontBytes = await fileToArrayBuffer(localFontFile);
            const font = await pdfDoc.embedFont(fontBytes);
            console.log('✓ 本地中文字体加载成功!');
            return { font, isChinese: true };
        } catch (error) {
            console.warn('本地字体加载失败:', error.message);
        }
    }

    // 尝试从CDN加载中文字体
    for (let i = 0; i < FONT_URLS.length; i++) {
        try {
            console.log(`尝试加载在线字体 (${i + 1}/${FONT_URLS.length})...`);
            const controller = new AbortController();
            const timeoutId = setTimeout(() => controller.abort(), 10000); // 10秒超时

            const response = await fetch(FONT_URLS[i], {
                mode: 'cors',
                cache: 'force-cache',
                signal: controller.signal
            });
            clearTimeout(timeoutId);

            if (!response.ok) {
                throw new Error(`HTTP ${response.status}`);
            }

            const fontBytes = await response.arrayBuffer();
            const font = await pdfDoc.embedFont(fontBytes);
            console.log('✓ 在线中文字体加载成功!');
            return { font, isChinese: true };
        } catch (error) {
            console.warn(`字体源 ${i + 1} 失败:`, error.message);
        }
    }

    // 所有字体源都失败，抛出错误
    throw new Error('无法加载中文字体！请上传本地字体文件（.ttf/.otf），或检查网络连接。\n\n推荐使用Windows自带字体：\n- C:\\Windows\\Fonts\\msyh.ttc (微软雅黑)\n- C:\\Windows\\Fonts\\simsun.ttc (宋体)');
}

// 生成PDF主函数
async function generatePDF() {
    if (!validateForm()) return;

    try {
        showProgress(true, 10, '创建PDF文档...');

        const data = getFormData();
        const pdfDoc = await PDFDocument.create();

        // 注册 fontkit（仅用于自定义字体）
        pdfDoc.registerFontkit(fontkit);

        // 加载字体 - 尝试多个源
        showProgress(true, 20, '加载字体...');
        const { font, isChinese } = await loadFont(pdfDoc);

        if (!isChinese) {
            console.warn('提示：当前使用标准字体，中文可能无法正常显示');
        }

        // 生成首页
        showProgress(true, 30, '生成首页...');
        addCoverPage(pdfDoc, data, font);

        // 生成内容
        showProgress(true, 50, '生成内容...');
        const pageMap = await addContent(pdfDoc, data, font);

        // 添加书签目录
        showProgress(true, 70, '添加目录书签...');
        addBookmarks(pdfDoc, pageMap);

        // 添加水印
        showProgress(true, 80, '添加水印...');
        addWatermark(pdfDoc, font);

        // 保存
        showProgress(true, 95, '保存文件...');
        const pdfBytes = await pdfDoc.save();

        // 下载
        let filename = `${data.basicInfo.city}${data.basicInfo.deliveryName}`;
        if (data.basicInfo.thirdPartyName) {
            filename += `致${data.basicInfo.thirdPartyName}`;
        }
        filename += `${data.basicInfo.caseType}案.pdf`;
        const blob = new Blob([pdfBytes], { type: 'application/pdf' });
        downloadFile(blob, filename);

        showProgress(true, 100, '完成！');
        setTimeout(() => {
            showProgress(false);
            showMessage('PDF生成成功！', 'success');
        }, 500);

    } catch (error) {
        showProgress(false);
        showMessage('生成失败: ' + error.message, 'error');
        console.error(error);
    }
}

// 添加首页
function addCoverPage(pdfDoc, data, font) {
    const page = pdfDoc.addPage([595, 842]);
    const { width, height } = page.getSize();

    let title = `${data.basicInfo.city}${data.basicInfo.deliveryName}`;
    if (data.basicInfo.thirdPartyName) {
        title += `致${data.basicInfo.thirdPartyName}`;
    }
    title += `${data.basicInfo.caseType}案`;

    const fontSize = 24;
    const textWidth = font.widthOfTextAtSize(title, fontSize);

    // 绘制标题
    page.drawText(title, {
        x: (width - textWidth) / 2,
        y: height / 2 + 30,
        size: fontSize,
        font: font,
        color: rgb(0, 0, 0)
    });

    // 绘制结案日期
    const dateSize = 14;
    const closeDate = `结案日期：${data.basicInfo.closeDate ? formatDate(data.basicInfo.closeDate) : '未结案'}`;
    
    const closeDateWidth = font.widthOfTextAtSize(closeDate, dateSize);

    page.drawText(closeDate, {
        x: (width - closeDateWidth) / 2,
        y: height / 2 - 15,
        size: dateSize,
        font: font,
        color: rgb(0.3, 0.3, 0.3)
    });
}

// 添加内容
async function addContent(pdfDoc, data, font) {
    const pageMap = {}; // 记录每个章节的页面索引
    const pages = pdfDoc.getPages();

    // 添加基本信息页
    const basicInfoPageIndex = pages.length;
    const page = pdfDoc.addPage([595, 842]);
    const { width, height } = page.getSize();
    let y = height - 60;

    pageMap['案件基本信息'] = basicInfoPageIndex;

    page.drawText('案件基本信息', {
        x: 50,
        y: y,
        size: 18,
        font: font,
        color: rgb(0, 0, 0)
    });

    y -= 40;

    const info = [
        ['闪送员姓名', data.basicInfo.deliveryName],
        ['三者姓名', data.basicInfo.thirdPartyName || '无'],
        ['案件类型', data.basicInfo.caseType],
        ['发案日期', formatDate(data.basicInfo.caseDate)],
        ['结案日期', formatDate(data.basicInfo.closeDate) || '未结案'],
        ['所属城市', data.basicInfo.city],
        ['案件责任人', data.basicInfo.caseHandler],
        ['案件描述', data.basicInfo.caseDesc]
    ];

    for (const [label, value] of info) {
        page.drawText(`${label}：`, {
            x: 50,
            y: y,
            size: 12,
            font: font
        });

        const lines = wrapText(value, font, 12, width - 200);
        lines.forEach((line, i) => {
            page.drawText(line, {
                x: 150,
                y: y - i * 20,
                size: 12,
                font: font,
                color: rgb(0.3, 0.3, 0.3)
            });
        });

        y -= Math.max(30, lines.length * 20 + 10);
    }

    // 添加材料章节
    for (let i = 0; i < data.materials.length; i++) {
        const material = data.materials[i];
        if (!material.description && (!material.files || !material.files.length)) continue;

        // 每个章节都从新页开始
        const sectionStartIndex = pdfDoc.getPages().length;
        pageMap[material.title] = sectionStartIndex;

        const sectionPage = pdfDoc.addPage([595, 842]);
        let sy = height - 60;

        // 绘制章节标题
        sectionPage.drawText(material.title, {
            x: 50,
            y: sy,
            size: 18,
            font: font
        });

        sy -= 40;

        // 绘制描述文字
        if (material.description) {
            const lines = wrapText(material.description, font, 12, width - 100);
            lines.forEach(line => {
                if (sy > 50) {
                    sectionPage.drawText(line, {
                        x: 50,
                        y: sy,
                        size: 12,
                        font: font,
                        color: rgb(0.3, 0.3, 0.3)
                    });
                    sy -= 20;
                }
            });
            sy -= 10; // 描述和图片之间的间距
        }

        // 添加文件
        if (material.files && material.files.length > 0) {
            // 分离图片和PDF
            const images = material.files.filter(f => f.type.startsWith('image/'));
            const pdfs = material.files.filter(f => f.type === 'application/pdf');
            
            // 在当前页面添加图片（从sy位置开始）
            if (images.length > 0) {
                sy = await addImagesInline(pdfDoc, images, sectionPage, sy, font, width, height);
            }
            
            // PDF文件单独页面
            for (const fileData of pdfs) {
                await embedPDF(pdfDoc, fileData.file);
            }
        }
        
        // 当前章节处理完毕，确保下一个章节从新页开始（已通过循环开始时的addPage实现）
    }

    return pageMap;
}

// 在页面内添加多张图片（紧凑排列）
async function addImagesInline(pdfDoc, imageFiles, currentPage, startY, font, pageWidth, pageHeight) {
    const margin = 50;
    const maxImageWidth = pageWidth - 2 * margin; // 左右各留50边距
    const maxImageHeight = 220; // 每张图片最大高度
    let currentY = startY;
    let currentPageObj = currentPage;
    
    for (const fileData of imageFiles) {
        // 加载图片
        const arrayBuffer = await fileToArrayBuffer(fileData.file);
        let image;
        let embedded = false;
        
        // 智能尝试加载图片
        const isPng = fileData.type === 'image/png' || fileData.file.name.toLowerCase().endsWith('.png');
        const isJpg = fileData.type === 'image/jpeg' || fileData.type === 'image/jpg' ||
                      fileData.file.name.toLowerCase().endsWith('.jpg') ||
                      fileData.file.name.toLowerCase().endsWith('.jpeg');
        
        if (isPng && !isJpg) {
            try {
                image = await pdfDoc.embedPng(arrayBuffer);
                embedded = true;
            } catch (error) {
                try {
                    image = await pdfDoc.embedJpg(arrayBuffer);
                    embedded = true;
                } catch (jpgError) {
                    console.error('两种格式都失败:', fileData.file.name);
                    continue;
                }
            }
        } else {
            try {
                image = await pdfDoc.embedJpg(arrayBuffer);
                embedded = true;
            } catch (error) {
                try {
                    image = await pdfDoc.embedPng(arrayBuffer);
                    embedded = true;
                } catch (pngError) {
                    console.error('两种格式都失败:', fileData.file.name);
                    continue;
                }
            }
        }
        
        if (!embedded) continue;
        
        // 计算图片缩放后的尺寸
        const scale = Math.min(maxImageWidth / image.width, maxImageHeight / image.height, 1);
        const imgWidth = image.width * scale;
        const imgHeight = image.height * scale;
        
        // 检查当前页面是否有足够空间（图片+文件名+间距）
        const requiredSpace = imgHeight + 30; // 图片高度 + 文件名空间 + 间距
        
        if (currentY - requiredSpace < margin) {
            // 空间不足，创建新页面
            currentPageObj = pdfDoc.addPage([pageWidth, pageHeight]);
            currentY = pageHeight - margin;
        }
        
        // 绘制图片（居中）
        currentPageObj.drawImage(image, {
            x: (pageWidth - imgWidth) / 2,
            y: currentY - imgHeight,
            width: imgWidth,
            height: imgHeight
        });
        
        currentY -= imgHeight;
        
        // 绘制文件名（居中，在图片下方）
        const fileName = fileData.file.name;
        const fileNameSize = 10;
        const fileNameWidth = font.widthOfTextAtSize(fileName, fileNameSize);
        
        currentPageObj.drawText(fileName, {
            x: (pageWidth - fileNameWidth) / 2,
            y: currentY - 15,
            size: fileNameSize,
            font: font,
            color: rgb(0.5, 0.5, 0.5)
        });
        
        currentY -= 30; // 移到下一张图片的位置（包含文件名和间距）
    }
    
    return currentY;
}

// 添加图片（已废弃，保留用于兼容）
async function addImage(pdfDoc, file) {
    const arrayBuffer = await fileToArrayBuffer(file);

    let image;
    let embedded = false;

    // 方案1: 根据文件扩展名和MIME类型判断
    const isPng = file.type === 'image/png' || file.name.toLowerCase().endsWith('.png');
    const isJpg = file.type === 'image/jpeg' || file.type === 'image/jpg' ||
                  file.name.toLowerCase().endsWith('.jpg') ||
                  file.name.toLowerCase().endsWith('.jpeg');

    // 方案2: 智能尝试 - 先尝试对应格式,失败则尝试另一种
    if (isPng && !isJpg) {
        try {
            image = await pdfDoc.embedPng(arrayBuffer);
            embedded = true;
        } catch (error) {
            console.warn(`${file.name} 标记为PNG但嵌入失败,尝试JPG格式...`);
            try {
                image = await pdfDoc.embedJpg(arrayBuffer);
                embedded = true;
            } catch (jpgError) {
                console.error('两种格式都失败:', file.name);
            }
        }
    } else {
        // 默认先尝试 JPG
        try {
            image = await pdfDoc.embedJpg(arrayBuffer);
            embedded = true;
        } catch (error) {
            console.warn(`${file.name} JPG格式嵌入失败,尝试PNG格式...`);
            try {
                image = await pdfDoc.embedPng(arrayBuffer);
                embedded = true;
            } catch (pngError) {
                console.error('两种格式都失败:', file.name);
            }
        }
    }

    if (!embedded) {
        throw new Error(`无法嵌入图片 ${file.name}: 不支持的图片格式或文件损坏`);
    }

    const page = pdfDoc.addPage([595, 842]);
    const { width, height } = page.getSize();

    const scale = Math.min((width - 100) / image.width, (height - 100) / image.height, 1);
    const imgWidth = image.width * scale;
    const imgHeight = image.height * scale;

    page.drawImage(image, {
        x: (width - imgWidth) / 2,
        y: (height - imgHeight) / 2,
        width: imgWidth,
        height: imgHeight
    });
}

// 嵌入PDF
async function embedPDF(pdfDoc, file) {
    const arrayBuffer = await fileToArrayBuffer(file);
    const externalPdf = await PDFDocument.load(arrayBuffer);
    const pages = await pdfDoc.copyPages(externalPdf, externalPdf.getPageIndices());
    pages.forEach(page => pdfDoc.addPage(page));
}

// 添加书签目录
function addBookmarks(pdfDoc, pageMap) {
    try {
        const pages = pdfDoc.getPages();
        const { PDFName, PDFArray, PDFDict, PDFNumber, PDFHexString, PDFRef } = PDFLib;
        const context = pdfDoc.context;

        // 创建书签项引用数组
        const outlineItemRefs = [];
        const outlineItems = [];

        // 先创建所有书签项的引用
        Object.entries(pageMap).forEach(([title, pageIndex]) => {
            if (pageIndex < pages.length) {
                const ref = context.nextRef();
                outlineItemRefs.push(ref);
                outlineItems.push({ title, pageIndex, ref });
            }
        });

        if (outlineItems.length === 0) {
            console.log('没有书签项需要添加');
            return;
        }

        // 创建 Outlines 字典引用
        const outlinesRef = context.nextRef();

        // 创建 Outlines 字典
        const outlinesDict = context.obj({
            Type: PDFName.of('Outlines'),
            Count: PDFNumber.of(outlineItems.length),
            First: outlineItemRefs[0],
            Last: outlineItemRefs[outlineItemRefs.length - 1]
        });

        // 为每个书签项创建字典
        outlineItems.forEach((item, index) => {
            const page = pages[item.pageIndex];
            const pageRef = page.ref;
            const pageHeight = page.getHeight();

            const outlineDict = {
                Title: PDFHexString.fromText(item.title),
                Parent: outlinesRef,
                Dest: context.obj([pageRef, PDFName.of('XYZ'), PDFNumber.of(0), PDFNumber.of(pageHeight), PDFNumber.of(0)])
            };

            // 添加前后链接
            if (index > 0) {
                outlineDict.Prev = outlineItemRefs[index - 1];
            }
            if (index < outlineItems.length - 1) {
                outlineDict.Next = outlineItemRefs[index + 1];
            }

            context.assign(item.ref, context.obj(outlineDict));
        });

        // 注册 Outlines 字典
        context.assign(outlinesRef, outlinesDict);

        // 将 Outlines 添加到 Catalog
        pdfDoc.catalog.set(PDFName.of('Outlines'), outlinesRef);

        console.log('✓ 已添加书签目录:', outlineItems.length, '个章节');
    } catch (error) {
        console.warn('书签添加失败:', error.message);
        console.warn('PDF 将生成但不包含书签目录');
    }
}

// 添加水印
function addWatermark(pdfDoc, font) {
    const pages = pdfDoc.getPages();
    const watermark = '危机处置部';

    pages.forEach(page => {
        const { width, height } = page.getSize();

        // 绘制多个水印
        const positions = [
            { x: width / 2 - 200, y: height / 2 + 200 },
            { x: width / 2 + 200, y: height / 2 + 200 },
            { x: width / 2, y: height / 2 },
            { x: width / 2 - 200, y: height / 2 - 200 },
            { x: width / 2 + 200, y: height / 2 - 200 }
        ];

        positions.forEach(pos => {
            const textWidth = font.widthOfTextAtSize(watermark, 60);
            page.drawText(watermark, {
                x: pos.x - textWidth / 2,
                y: pos.y,
                size: 60,
                font: font,
                color: rgb(0.85, 0.85, 0.85),
                opacity: 0.3,
                rotate: degrees(-45)
            });
        });
    });
}